/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.cognition.util.marshal;

/**
 * Marshall's integer types.
 * @author richard
 */
public class IntegerMarshaller {
    public static final int MARSHAL_SIZE = 4; // bytes

    /**
     * Converts a the first four bytes of a byte array into an integer.
     * @param b the byte array to convert.
     * @return an integer
     * @throws IllegalArgumentException if the byte array is null or is less
     *      than four bytes in length.
     */
    public static int unmarshal(byte[] b) throws IllegalArgumentException {
        if (b == null || b.length < MARSHAL_SIZE)
            throw new IllegalArgumentException(
                    "Cannot unmarshal a byte array that is null or too short.");

        return (int)(
            (int) (0xff & b[0]) << 24 |
            (int) (0xff & b[1]) << 16 |
            (int) (0xff & b[2]) << 8 |
            (int) (0xff & b[3]) << 0);

    }

    /**
     * Converts an integer into a four byte array.  Storage is most
     * significant byte first order (Big Endian).
     * @param i the integer to convert
     * @return the byte representation of the integer.
     */
    public static byte[] marshal(int i){
            return new byte[]{
                (byte) ((i >> 24) & 0xff),
                (byte) ((i >> 16) & 0xff),
                (byte) ((i >> 8) & 0xff),
                (byte) ((i >> 0) & 0xff)
            };

    }

}
